import dxMap from '../../dxmodules/dxMap.js'
import dxui from '../../dxmodules/dxUi.js'
// Language pack
import messages from '../../resource/langPack.js'

class I18n {
    constructor() {
        const i18nMap = dxMap.get("i18n")
        this.locale = i18nMap.get("language") || 'EN'
        this.fallbackLocale = 'EN'
    }

    // Get the translated text
    t(key) {
        const keys = key.split('.')
        let result = messages[this.locale]

        for (const k of keys) {
            if (result && result[k]) {
                result = result[k]
            } else {
                // If no translation is found for the current language, use the alternative language.
                result = this._getFallbackText(key)
                break
            }
        }

        return result || key
    }

    // Get translations for alternative languages
    _getFallbackText(key) {
        const keys = key.split('.')
        let result = messages[this.fallbackLocale]

        for (const k of keys) {
            if (result && result[k]) {
                result = result[k]
            } else {
                return key
            }
        }

        return result
    }

    // refresh
    refresh() {
        for (const key in dxui.all) {
            const obj = dxui.all[key]
            if (obj.dataI18n) {
                obj.text(this.t(obj.dataI18n))
            }
        }
    }

    // Refresh the specified object
    refreshObj(obj) {
        if (obj.dataI18n) {
            obj.text(this.t(obj.dataI18n))
        }
    }

    // Switch language
    setLanguage(lang) {
        if (messages[lang]) {
            this.locale = lang
            dxMap.get("i18n").put("language", lang)
            // Trigger a custom event to notify of language changes
            for (const key in dxui.all) {
                const obj = dxui.all[key]
                if (obj.dataI18n) {
                    obj.text(this.t(obj.dataI18n))
                }
            }
        }
    }
}

// Create a singleton
const i18n = new I18n()
export default i18n
